import Vue from 'vue'
import VueRouter from 'vue-router'
import { constantRouterMap } from './router.config.js'

// 解决路由报错问题（当页面再次进入同一个路由地址时，控制台报错）
// 官方解释: In 3.1.0+, you can omit the 2nd and 3rd parameter and router.push/router.replace will return a promise instead if Promises are supported
// 2.2.0+版本vue-router重写push方法只需传入一个参数即可, 3.1.0+则需传入三个参数

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const createRouter = () =>
  new VueRouter({
    mode: 'history', // 如果你是 history模式 需要配置vue.config.js publicPath
    // base: process.env.BASE_URL,
    routes: constantRouterMap
  })

const router = createRouter()

export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

export default router
